package com.homework1;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Unzip implements Runnable {
    
    private String filePath;
    private StringBuilder filesContent;
    
    public Unzip(String filePath){
	this.filePath = filePath;
    }

    @Override
    public void run() {
	
	byte[] buffer = new byte[1024];
	
	try {
	    ZipInputStream zis = new ZipInputStream(new FileInputStream(filePath));
	    ZipEntry ze = zis.getNextEntry();
	    
	    while(ze!=null){
		
		filesContent = new StringBuilder();
		
		int len;
		while((len = zis.read(buffer))>0){
		    filesContent.append(buffer);
		}
		
		ze = zis.getNextEntry();
		
	    }
	    
	    zis.closeEntry();
	    zis.close();
	    
	    System.out.println("Readed text: " + filesContent);
	    
	    
	} catch (FileNotFoundException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	
	if(filesContent.length()!=0)
	writeToFile(filesContent);
    }
    
    private void writeToFile(StringBuilder sb){
	String textToCompress = sb.toString();
	BufferedWriter writer = null;
	
	try {
	    writer = new BufferedWriter(new FileWriter("alltext.txt"));
	    writer.write(textToCompress);
	} catch (FileNotFoundException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	finally{
	   try {
	    writer.close();
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	}
    }
    
    

}
